import { Button, message, Input, Modal, Form, Switch, Upload, Popconfirm, InputNumber } from 'antd';
import React, { useState, useRef } from 'react';
import { useIntl, FormattedMessage } from 'umi';
import { PageContainer, FooterToolbar } from '@ant-design/pro-layout';
import ProTable from '@ant-design/pro-table';
import { UploadOutlined, AudioOutlined, AudioMutedOutlined } from '@ant-design/icons';
import {
  getAudioList,
  fileUpload,
  updateAudio,
  addAudio,
  removeAudio,
  setRefreshTime,
  getRefreshTime,
} from '@/services';

const Audio = () => {
  const intl = useIntl();
  const actionRef = useRef(null);
  const [visible, setVisible] = useState(false);
  const [visibleRefresh, setVisibleRefresh] = useState(false);
  const [submitting, setSubmitting] = useState(false);
  const [submittingRefresh, setSubmittingRefresh] = useState(false);
  const [updateId, setUpdateId] = useState(null);
  const [fileList, setFileList] = useState([]);

  const [title, setTitle] = useState(
    intl.formatMessage({
      id: 'pages.add',
    }),
  );

  const [form] = Form.useForm();
  const [formRefresh] = Form.useForm();

  const handleAdd = () => {
    setVisible(true);
    setTitle(
      intl.formatMessage({
        id: 'pages.add',
      }),
    );
  };
  const handleRefresh = async () => {
    setVisibleRefresh(true);
    const res = await getRefreshTime(1);
    console.log('res', res);
    if (res) {
      formRefresh.setFields([
        {
          name: 'warningFrequency',
          value: res.data.value,
        },
      ]);
    }
  };
  const handleUpdate = (record) => {
    setVisible(true);
    setTitle(
      intl.formatMessage({
        id: 'pages.update',
      }),
    );
    setUpdateId(record.id);
    form.setFieldsValue(record);
    record.audioUrl &&
      setFileList([
        {
          url: record.url,
          name: record.audioName,
          status: 'done',
          uid: '-1',
        },
      ]);
  };
  const handleRemove = async (record) => {
    const res = await removeAudio({ id: record.id });
    if (res) {
      message.success(
        intl.formatMessage({
          id: 'pages.success',
        }),
      );
      actionRef.current?.reload();
    }
  };
  const handleCancel = () => {
    setVisible(false);
    form.resetFields();
    setUpdateId(null);
    setFileList([]);
  };

  const handleOk = async () => {
    await form.validateFields();
    let values = form.getFieldsValue();
    setSubmitting(true);
    const func = updateId ? updateAudio : addAudio;
    const res = await func({
      id: updateId,
      ...values,
      audioUrl: fileList[0].url,
    });
    if (res) {
      message.success(
        intl.formatMessage({
          id: 'pages.success',
        }),
      );
      handleCancel();
      actionRef?.current?.reload();
    }
    setSubmitting(false);
  };

  const handleCancelRefresh = () => {
    setVisibleRefresh(false);
    formRefresh.resetFields();
    setSubmittingRefresh(false);
  };

  const handleOkRefresh = async () => {
    await formRefresh.validateFields();
    let values = formRefresh.getFieldsValue();
    setSubmittingRefresh(true);
    const res = await setRefreshTime({
      value: values.warningFrequency,
      id: 1,
    });
    if (res) {
      message.success(
        intl.formatMessage({
          id: 'pages.success',
        }),
      );
      handleCancelRefresh();
    }
  };

  const play = (checked, record) => {
    let audio = document.getElementById(`audio_${record.audioUrl}`);
    if (audio.paused) {
      checked && audio.play();
    } else {
      !checked && audio.pause();
    }
  };

  const columns = [
    {
      title: <FormattedMessage id="pages.audio.audioName" defaultMessage="铃声名称" />,
      dataIndex: 'audioName',
    },
    {
      title: <FormattedMessage id="pages.audio.audioUrl" defaultMessage="铃声地址" />,
      dataIndex: 'audioUrl',
      render: (_, record) => {
        return (
          <>
            <Switch
              onChange={(val) => play(val, record)}
              checkedChildren={<AudioOutlined />}
              unCheckedChildren={<AudioMutedOutlined />}
            />
            <audio id={`audio_${record.audioUrl}`} src={record.audioUrl}></audio>
          </>
        );
      },
    },
    {
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',
      render: (_, record) => [
        <Button key="update" size="small" onClick={() => handleUpdate(record)} type="success">
          <FormattedMessage id="pages.update" defaultMessage="修改" />
        </Button>,
        <Popconfirm
          key="delete"
          title={<FormattedMessage id="pages.delete_confirm" />}
          onConfirm={() => handleRemove(record)}
        >
          <Button size="small" type="danger">
            <FormattedMessage id="pages.delete" defaultMessage="删除" />
          </Button>
        </Popconfirm>,
      ],
    },
  ];

  const queryList = async (params) => {
    const res = await getAudioList({
      ...params,
    });
    if (res) {
      return res;
    }
  };

  const beforeUpload = async (file, fileList) => {
    if (file.type !== 'audio/mp3' && file.type !== 'audio/mpeg') {
      return message.info(intl.formatMessage({ id: 'pages.audio.p_mp3' }));
    }
    const formData = new FormData();
    formData.append('file', file);
    const res = await fileUpload(formData);
    if (res) {
      fileList = fileList.map((item) => {
        item.url = res.url;
        return item;
      });
      setFileList(fileList);
    }
    return false;
  };

  return (
    <PageContainer>
      <ProTable
        actionRef={actionRef}
        rowKey="id"
        search={false}
        toolBarRender={() => [
          <Button key="show" type="primary" onClick={handleRefresh}>
            <FormattedMessage id="pages.setRefreshTime" defaultMessage="设置全局报警频率" />
          </Button>,
          <Button key="add" type="primary" onClick={handleAdd}>
            <FormattedMessage id="pages.add" defaultMessage="增加" />
          </Button>,
        ]}
        request={(params, sorter, filter) => queryList({ ...params })}
        columns={columns}
      />

      <Modal
        title={title}
        visible={visible}
        onOk={handleOk}
        onCancel={handleCancel}
        confirmLoading={submitting}
      >
        <Form form={form} labelCol={{ span: 6 }}>
          <Form.Item
            label={<FormattedMessage id="pages.audio.audioName" defaultMessage="铃声名称" />}
            name="audioName"
            rules={[
              { required: true, message: intl.formatMessage({ id: 'pages.audio.p_audioName' }) },
            ]}
          >
            <Input />
          </Form.Item>
          <Form.Item
            label={<FormattedMessage id="pages.audio.audioUrl" defaultMessage="铃声" />}
            name="audioUrl"
            rules={[
              { required: true, message: intl.formatMessage({ id: 'pages.audio.p_audioUrl' }) },
            ]}
          >
            <Upload fileList={fileList} name="logo" beforeUpload={beforeUpload}>
              <Button icon={<UploadOutlined />}>
                <FormattedMessage id="pages.clickUpload" defaultMessage="上传" />
              </Button>
            </Upload>
          </Form.Item>
        </Form>
      </Modal>

      <Modal
        title={<FormattedMessage id="pages.setRefreshTime" defaultMessage="设置全局报警频率" />}
        visible={visibleRefresh}
        onOk={handleOkRefresh}
        onCancel={handleCancelRefresh}
        confirmLoading={submittingRefresh}
      >
        <Form form={formRefresh} labelCol={{ span: 6 }}>
          <Form.Item
            label={<FormattedMessage id="pages.warningFrequency" defaultMessage="报警频率（秒）" />}
            name="warningFrequency"
            rules={[
              { required: true, message: intl.formatMessage({ id: 'pages.p_warningFrequency' }) },
            ]}
          >
            <InputNumber style={{ width: '100%' }} />
          </Form.Item>
        </Form>
      </Modal>
    </PageContainer>
  );
};

export default Audio;
